#include<vector>
#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
#include<set>
#include<queue>
using namespace std;
class Solution {
public:
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    int nearestExit(vector<vector<char>>& maze, vector<int>& e) {
        int m = maze.size(), n = maze[0].size();
        bool visted[m][n];
        memset(visted, 0, sizeof(visted));
        queue<pair<int, int>> q;
        q.push({ e[0],e[1] });
        visted[e[0]][e[1]] = true;
        int step = 0;
        while (!q.empty()) {
            int se = q.size();
            step++;
            for (int i = 0; i < se; i++) {
                auto [a, b] = q.front();
                q.pop();
                for (int j = 0; j < 4; j++) {
                    int x = a + dx[j];
                    int y = b + dy[j];
                    if (x >= 0 && x < m && y >= 0 && y < n
                        && maze[x][y] == '.'
                        && visted[x][y] == false) {
                        if (x == 0 || y == 0 || x == m - 1 || y == n - 1) {
                            return step;
                        }
                        q.push({ x,y });
                        visted[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
};